import { list as menuList } from '../../api/common/menu.js'
import { loginByUsername, logout, getUserInfo } from '../../api/login.js'
import { getToken, setToken, removeToken } from '../../utils/auth'
import { dgTree } from '../../utils/index.js';
import { asyncRouterMap } from '../../router/index.js';

const user = {
    state: {
        user: '',
        status: '',
        code: '',
        token: getToken(),
        name: '',
        avatar: '',
        introduction: '',
        roles: [],
        setting: {
            articlePlatform: []
        }
    },

    mutations: {
        SET_CODE: (state, code) => {
            state.code = code
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_INTRODUCTION: (state, introduction) => {
            state.introduction = introduction
        },
        SET_SETTING: (state, setting) => {
            state.setting = setting
        },
        SET_STATUS: (state, status) => {
            state.status = status
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        }
    },

    actions: {
        // 用户名登录
        LoginByUsername ({ commit }, userInfo) {
            const username = userInfo.username.trim()
            return new Promise((resolve, reject) => {
                loginByUsername(username, userInfo.password).then(response => {
                    console.log(response)
                    const data = response.data
                    commit('SET_TOKEN', data.token)
                    setToken(response.data.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetUserInfo ({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo(state.token).then(res => {
                    if (!res.data) { // 由于mockjs 不支持自定义状态码只能这样hack
                        reject('error')
                    }
                    const data = res.data

                    commit('SET_ROLES', ['admin']);

                    // if (data.admin_role_name && data.admin_role_name.length > 0) { // 验证返回的roles是否是一个非空数组
                    //     commit('SET_ROLES', [data.admin_role_name])
                    // } else {
                    //     reject('getInfo: roles must be a non-null array !')
                    // }
                    commit('SET_NAME', data.username)
                    commit('SET_AVATAR', data.username)
                    commit('SET_INTRODUCTION', data.introduction)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获菜单
        getMenu ({ commit, state }, roles) {
            return new Promise((resolve, reject) => {
                menuList({menu_pid: 0}).then(res => {
                    let routerList = [];
                    for (let item of asyncRouterMap[0].children) {
                        for (let item2 of res.data.list) {
                            if (item2.menu_path === item.path) {
                                !item.meta && (item.meta = {});
                                item.meta.title = item2.menu_title;
                                item.meta.icon = item2.menu_icon;
                                routerList.push(item);
                                break;
                            }
                        }
                    }
                    asyncRouterMap[0].children = routerList;
                    // commit('SET_ROLES', [data.admin_role_name])
                    commit('SET_ROUTERS', asyncRouterMap);
                    resolve(asyncRouterMap);
                    // console.log(routerList);
                    // asyncRouterMap
                    // if (res.errno === 0) {
                    //     let menuList = res.data.list;
                    //     let routerList = [];
                    //     for (let item2 of menuList) {
                    //         let item = {};
                    //         dgTree(res.data.children, item3 => {
                    //             if (item3.menu_id === item2.menu_id) {
                    //                 item = item3;
                    //             }
                    //         }, 'children');
                    //         // pid
                    //         let pPath = '';
                    //         dgTree(res.data.children, item3 => {
                    //             if (item.menu_pid === item3.menu_id) {
                    //                 pPath = item3.menu_path;
                    //             }
                    //         }, 'children');
                    //         if ('children' in item && item.children.length > 0) {
                    //             routerList.push({
                    //                 path: item.menu_path,
                    //                 name: item.menu_name,
                    //                 redirect: item.children[0].path,
                    //                 pPath: pPath,
                    //                 meta: { title: item.menu_title, icon: item.menu_icon, noCache: true }
                    //             });
                    //         } else {
                    //             if (item.menu_path && item.menu_path.length > 0) {
                    //                 routerList.push({
                    //                     path: item.menu_path,
                    //                     component: () => resolve => require(['@/views/' + item.menu_path], resolve),
                    //                     name: item.menu_name,
                    //                     pPath: pPath,
                    //                     meta: { title: item.menu_title, icon: item.menu_icon, noCache: true }
                    //                 });
                    //             }
                    //         }
                    //     }
                        
                    //     console.log(roles)
                    //     //
                    // }
                    
                    // console.log(res);
                    // let menuList = res
                    // if (!res.data) { // 由于mockjs 不支持自定义状态码只能这样hack
                    //     reject('error')
                    // }
                    // const data = res.data

                    // // if (data.admin_role_name && data.admin_role_name.length > 0) { // 验证返回的roles是否是一个非空数组
                    // //     commit('SET_ROLES', [data.admin_role_name])
                    // // } else {
                    // //     reject('getInfo: roles must be a non-null array !')
                    // // }
                    // commit('SET_NAME', data.username)
                    // commit('SET_AVATAR', data.username)
                    // commit('SET_INTRODUCTION', data.introduction)
                    // resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 第三方验证登录
        // LoginByThirdparty({ commit, state }, code) {
        //   return new Promise((resolve, reject) => {
        //     commit('SET_CODE', code)
        //     loginByThirdparty(state.status, state.email, state.code).then(response => {
        //       commit('SET_TOKEN', response.data.token)
        //       setToken(response.data.token)
        //       resolve()
        //     }).catch(error => {
        //       reject(error)
        //     })
        //   })
        // },

        // 登出
        LogOut ({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 前端 登出
        FedLogOut ({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        },

        // 动态修改权限
        ChangeRoles ({ commit, dispatch }, role) {
            return new Promise(resolve => {
                commit('SET_TOKEN', role)
                setToken(role)
                getUserInfo(role).then(response => {
                    const data = response.data
                    commit('SET_ROLES', data.roles)
                    commit('SET_NAME', data.name)
                    commit('SET_AVATAR', data.avatar)
                    commit('SET_INTRODUCTION', data.introduction)
                    dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
                    resolve()
                })
            })
        }
    }
}

export default user
